package com.example.demo.api;

import com.example.demo.model.Friend;
import com.example.demo.model.MessageSession;
import com.example.demo.model.MessageSessionMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MessageSessionAPI {
    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @RequestMapping("/sessionList")
    @ResponseBody
    public Object getMessageSessionList(HttpServletRequest request) {
        List<MessageSession> messageSessionList = new ArrayList<>();
        // 获取当前用户的userId 从session中获取
        HttpSession session = request.getSession(false);
        if(session == null) {
            System.out.println("[getMessageSessionList] session == null");
            return messageSessionList;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            System.out.println("[getMessageSessionList] user == null");
            return messageSessionList;
        }
        // 根据Userid 查到与之相关的会还
        List<Integer> sessionIdList = messageSessionMapper.getSessionIdsByUserId(user.getUserId());
        for (int sessionId : sessionIdList) {
            MessageSession messageSession = new MessageSession();
            // 遍历会话id 查询出每个好友
            List<Friend> friends = messageSessionMapper.getFriendsBySessionId(sessionId, user.getUserId());
            messageSession.setSessionId(sessionId);
            messageSession.setFriends(friends);
            // TODO: 遍历会话id 查出每个会话的最后一条消息
            messageSession.setLastMessage("出去玩");
            messageSessionList.add(messageSession);
        }
        // 构造出messageSession对象数组
        return messageSessionList;
    }
}
